import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2024-02-13
 * Time:19:51
 */
public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75f; //默认载荷因子阈值
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public HashBucket() {
        array = new Node[DEFAULT_SIZE];
    }

    private double loadFactor() {
        return size * 1.0 / array.length;
    }

    public void put(int key, int value) {
        int hash = key % array.length; //计算地址
        Node cur = array[hash];
        while(cur != null) {  //先找一下key是否已经存在，若已经存在，则更新它的value就可以了
            if(cur.key == key) {
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        //到这里说明没找到key，那么就创建新节点，然后头插
        Node node = new Node(key,value);
        node.next = array[hash];
        array[hash] = node;
        size++;
        if(loadFactor() > LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {
        Node[] newArray = new Node[array.length*2];
        for(int i = 0;i < array.length;i++) {
            Node cur = array[i];
            //遍历链表
            while(cur != null) {
                Node tmp = cur.next;  //先保存 cur 的下一个节点，不然头插后会找不到它
                int newIndex = i % newArray.length;
                //采用头插法 插入到新数组的 newIndex下标
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = tmp;
            }
        }
        array = newArray;
    }

    public int get(int key) {
        int hash = key % array.length;
        Node node = array[hash];

        while(node != null) {
            if(node.key == key)
                return node.value;
            node = node.next;
        }
        return -1;
    }
}
